#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <string.h>
#include <limits.h>
#include <unistd.h>
#include <sys/time.h>

#include "list.h"					  /* use the SimCList library */
#include "utils.h"

#define TRUE 1
#define FALSE 0

int compint(const void *a,const void *b) {
	return( (*(int *)a < *(int *)b)?1:0 );
}

int compint2(const void *a,const void *b) {
	return( (*(int *)a < *(int *)b)?0:1 );
}


int main(int argc,char **argv)
{
	struct timeval tmv;
	list *mylist;					  /* declare a list */
	int userval;
	int i,*rnum;
	
	listIter *iter;
	listNode  *node;

	mylist = listCreate();		  /* initialize the list */
	mylist->free = free;
        mylist->sort_threads = 4;

	memset(&tmv,0x0,sizeof(struct timeval));

	userval = atol(argv[1]);	
	printf("generate random %10d integer num",userval);
	for (i = 0; i<userval ; i++) {
		rnum = calloc(1,sizeof(int));
		*rnum = randi(1000000);
		listAddNodeTail(mylist, rnum);	/* add an element to the list */
		}
	printf("\n");

	printf("The list now holds %u elements.\n", listLength(mylist));	/* get the size of the list */
	tic(&tmv);
	//for ( i = 0 ; i<2048; i++){
	list_qsort(mylist,compint);
	//list_qsort(mylist,compint2);
	//}
	//listQuickSort(mylist->head,mylist->tail,compint);
	//listQuickSort(mylist->head,mylist->tail,compint2);
	toc(&tmv);

	printf("\nfirst 50 is ");
        iter=listGetIterator(mylist,AL_START_HEAD);
	i = 0;
	while ((node = listNext(iter)) != NULL) {
		;;
		if(++i < 50 ) 
		printf("%8d", *(int *)node->value);
	}
	listReleaseIterator(iter);
	printf("\nlast 50 is ");
        iter=listGetIterator(mylist,AL_START_TAIL);
	i = 0;
	while ((node = listNext(iter)) != NULL) {
		;;
		printf("%8d", *(int *)node->value);
		if(++i > 50 ) break;

	}
	listReleaseIterator(iter);

	printf("\n");

        iter=listGetIterator(mylist,AL_START_HEAD);
	i = 0;
	while ((node = listNext(iter)) != NULL) {
		;;
		++i  ; 
	}
	listReleaseIterator(iter);
	printf("\nlistLength %d i %d \n",listLength(mylist),i);

	listRelease(mylist);

	return 0;
}
